<?php
/**
 * 导入提货产品申请
 */
namespace App\Admin\Controllers\Shipping;

use App\Importer\Shipping\SkuImporter;
use App\Models\Basics\SysArea;
use App\Models\Product\ProductSku;
use App\Models\Shipping\SSku;
use App\Models\Shipping\SSkuApply;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class SkuUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        return view("shipping.sku.upload.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            $shippingDate = SSkuApply::initShippingDate();
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                if(!$_area || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $sSku = SSku::query()
                    ->where('area_id',$areaId)
                    ->where('psku_id',$pSkuId)
                    ->first();
                if(!$sSku){
                    $errors[$count] = $key.'系统不存在';
                    DB::rollBack();
                    continue;
                }
                if($sSku->status == 2){ //待审核
                    $errors[$count] = $key.'审批中勿修改';
                    DB::rollBack();
                    continue;
                }
                if($sSku->is_lock == 1){ //已锁定
                    $errors[$count] = $key.'锁定中勿修改';
                    DB::rollBack();
                    continue;
                }
                $applyNum = [];
                $error = '';
                $j = 2;
                foreach ($shippingDate as $date => $label){
                    $_applyNum = is_null($row[$j]) ? null : trim($row[$j]);
                    $j++;
                    if($_applyNum){
                        if(!is_numeric($_applyNum)){
                            $error = '提货数量格式有误';
                            break;
                        }
                        if($_applyNum < 0){
                            $error = '提货数量不能小于0';
                            break;
                        }
                    }
                    $applyNum[$date] = $_applyNum;
                }
                if(!empty($error)){
                    $errors[$count] = $key.$error;
                    DB::rollBack();
                    continue;
                }

                //更新提货sku
                $sSku->status = 2; //待审批
                $sSku->seller_id = $userId;
                $flag = $sSku->save();
                if(!$flag){
                    DB::rollBack();
                    continue;
                }

                //更新/创建提货申请
                $k = 0;
                foreach($applyNum as $date => $_applyNum){
                    if(!is_null($_applyNum)){
                        $sSkuApply = SSkuApply::query()->firstOrNew([
                            'area_id' => $areaId,
                            'psku_id' => $pSkuId,
                            'shipping_date' => $date,
                        ]);
                        $sSkuApply->last_apply_num = $sSkuApply->apply_num; //最后申请数量
                        $sSkuApply->apply_num = $_applyNum;
                        $flag1 = $sSkuApply->save();
                        $flag1 && $k++;
                    }else{
                        $k++;
                    }
                }
                if($k == count($shippingDate)){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
